<template>
  <!-- n-modal already had <teleport> directive -->
  <n-modal v-model:show="showModal">
    <n-card style="width: 600px" title="选择干员"
            :bordered="false" size="huge">
      <n-card v-for="k in charView.keys" :title="k.name">
        <!-- {{ charView[k.key] }} -->
        <n-space v-for="rarity in Object.keys(charView[k.key]).reverse()">
          <span v-if="rarity != 'default'">
            ☆ {{ parseInt(rarity)+1 }}
          </span>
          <n-button text v-for="item in charView[k.key][rarity]"
                    @click="onSelect(item)">
            {{ item.name }}
          </n-button>
        </n-space>
      </n-card>
    </n-card>
  </n-modal>
</template>

<script lang="ts" setup>
import { computed, ref, inject } from 'vue'
import { computedAsync } from '@vueuse/core'
import { useI18n } from 'vue-i18n'
import { NModal, NCard } from 'naive-ui'
import { apiGet } from '../utils'
import { ISelectedChar, ProfessionNames, NewOp } from '../utils/types'

// 传给该组件的参数，使用toRef取得响应式引用
// 值修改emit给上层组件
const props = defineProps({
  show: { type: Boolean, default: false },
  filter: { type: () => Boolean, default: null },
  debug: { type: Boolean, default: false },
  selected: {
    charId: String,
    name: String,
    default: null
  }
})

const emit = defineEmits({
  'update:show': Boolean,
  'update:selected': {
    charId: String,
    name: String
  }
})

// script setup上下文中不能使用Vue.$t，必须单独引入
const { t, locale } = useI18n() 

const evaluating = ref(false)
const charList = computedAsync(async () => await apiGet(`view/characterList/${locale.value}`),
                               null,
                               evaluating)

function buildItems(list: string[]): any {
  return list.map(x => ({
    charId: x,
    name: charList.value[x] ? charList.value[x].name: `(Not arrived: ${x})`
  }))
}

const charView = computed(() => {
  const view: any = {
    keys: []
  }

  if (charList.value) {
    // 获得过滤后的charKeys
    const cl = charList.value
    var charKeys = Object.keys(cl).filter(x => (!['TOKEN', 'TRAP'].includes(cl[x].profession)))
    if (props.filter) charKeys = charKeys.filter(x => props.filter(cl[x]))

    // new op
    view.keys.push({key: 'new_op', name: t('new_op')})
    view.new_op = { default: buildItems(NewOp) }

    // sub op
    if (props.selected && props.selected.charId) {
      view.keys.push({key: 'sub_op', name: t('sub_op')})
      view.sub_op = { default: buildItems(charKeys.filter(x => cl[x].subProfessionId == cl[props.selected.charId].subProfessionId)) }
    }

    Object.keys(ProfessionNames).forEach(k => {
      view.keys.push({key: k, name: ProfessionNames[k][locale.value]})
      view[k] = {}
    })

    charKeys.forEach(key => {
      const ch = cl[key]
      if (!view[ch.profession][ch.rarity])
        view[ch.profession][ch.rarity] = []
      view[ch.profession][ch.rarity].push({charId: key, name: ch.name})
    })
    if (props.debug) console.log(charList.value, view)
  }
  return view
})

const showModal = computed({
  get () { return props.show },
  set (_new: boolean) {
    // emit the new value to parent component, which uses v-model to watch
    // console.log('showModal.set() -> ', _new)
    emit('update:show', _new) 
  }
})

const onSelect = (ch: ISelectedChar) => {
  emit('update:selected', ch)
  showModal.value = false
}

</script>